//
//  PictureViewController.m
//  FuncFanc
//
//  Created by hubing on 2018/3/5.
//  Copyright © 2018年 huhu. All rights reserved.
//

#import "PictureViewController.h"
#import "CollectionViewCell.h"
#import "ChatImageBrowserView.h"


@interface PictureViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>
@property (nonatomic, strong) UICollectionView *collectView;
@property (nonatomic, strong) UICollectionViewFlowLayout *layout;
@property (nonatomic, strong) NSArray *dataList;
@property (nonatomic, strong) NSString *url;
@property (nonatomic, strong) UIButton *refreshBtn;
@property (nonatomic, strong) UILabel *tipLabel;


@end

@implementation PictureViewController

static NSString *const cellId = @"cellId";
static NSString *const headerId = @"headerId";
static NSString *const footerId = @"footerId";


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor clearColor];
    _url = @"http://api.isoyu.com/index.php/api/Picture/hua_ban";
//    self.title = @"花瓣美女";
//    NSArray *typeList = @[@"花瓣",@"cosplay"];
//    NSMutableArray *typeBtnArray = [NSMutableArray array];
//
//    for (int i = 0 ; i < typeList.count; i ++) {
//        UIBarButtonItem *btn = [[UIBarButtonItem alloc]initWithTitle:typeList[i] style:UIBarButtonItemStylePlain target:self action:@selector(changeVideoType:)];
//        btn.tag = i;
//        [btn setTintColor:[UIColor blackColor]];
//        [typeBtnArray addObject:btn];
//    }
//    self.navigationItem.leftBarButtonItems = typeBtnArray;
    
//
//
//
//
//    self.navigationItem.leftBarButtonItems = typeBtnArray;
//>>>>>>> 598c7455caa8a6b06442bc2bee9b0907214d18e5
    _layout = [[UICollectionViewFlowLayout alloc]init];
    [_layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    _layout.minimumLineSpacing = 0;
    _layout.minimumInteritemSpacing = 0;

//
//
//    _collectView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-40) collectionViewLayout:_layout];
    _collectView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) collectionViewLayout:_layout];
    
    _collectView.dataSource = self;
    _collectView.delegate = self;
    _collectView.bounces = YES;
    _collectView.alwaysBounceHorizontal = YES;
    _collectView.showsHorizontalScrollIndicator = NO;
    _collectView.scrollsToTop = YES;
    _collectView.pagingEnabled = YES;
    _collectView.backgroundColor = [UIColor clearColor];
    
    _collectView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(on_loadMore)];
    _collectView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(on_refresh)];
    [self.view addSubview:_collectView];
    [_collectView registerNib:[UINib nibWithNibName:@"CollectionViewCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"cellId"];
    [_collectView.mj_header beginRefreshing];
}

-(void)getData{
    __weak typeof(self) ws = self;
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy];
    securityPolicy.validatesDomainName = NO;
    securityPolicy.allowInvalidCertificates = YES;
    manager.securityPolicy = securityPolicy;
     manager.responseSerializer.acceptableContentTypes =[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html",@"text/plain", nil];
    [manager GET:_url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"code"]intValue] == 1) {
            [ws.collectView reloadData];
            _tipLabel.hidden = YES;
            _refreshBtn.hidden = YES;
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"网络连接错误%@",error);
    }];
}

-(void)on_refresh{
    __weak typeof(self) ws = self;
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:_url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"code"]intValue] == 1) {
          
            _tipLabel.hidden = YES;
            _refreshBtn.hidden = YES;
            ws.dataList = responseObject[@"data"];
            NSLog(@"%@",responseObject);
            [ws allLoadingCompleted];
            [_collectView setContentOffset:CGPointMake(0, 0) animated:NO];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        _refreshBtn.hidden = NO;
        _tipLabel.hidden = NO;
        [ws allLoadingCompleted];
    }];
}

-(void)allLoadingCompleted
{
    [_collectView.mj_header endRefreshing];
    [_collectView reloadData];
}


-(void)on_loadMore{
    __weak typeof(self) ws = self;
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:_url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"code"]intValue] == 1) {
            
            _tipLabel.hidden = YES;
            _refreshBtn.hidden = YES;
            ws.dataList = responseObject[@"data"];
            NSLog(@"%@",responseObject);
            [ws endLoad];
            [_collectView setContentOffset:CGPointMake(0, 0) animated:NO];
        }
      
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
        [ws endLoad];
    }];
}

-(void)endLoad{
 //   _isLoadMore = NO;
    [_collectView.mj_footer endRefreshing];
    [_collectView reloadData];
    if (_dataList.count == 0) {
        //   [self addNoDataView];
    }
}


-(void)noNetwork{
    
   _tipLabel = [[UILabel alloc]init];
    _tipLabel.text = @"未检测到网络连接，请在设置里检查是否允许拍拍使用网络";
    _tipLabel.textColor = [UIColor grayColor];
    _tipLabel.font = [UIFont systemFontOfSize:18];
    [self.view addSubview:_tipLabel];
    _tipLabel.numberOfLines = 0;
    _tipLabel.textAlignment = NSTextAlignmentCenter;
    _tipLabel.frame = CGRectMake(0, ScreenHeight/2, ScreenWidth, 80);
    _tipLabel.hidden = YES;
   
    
    _refreshBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_refreshBtn setTitle:@"刷新" forState:UIControlStateNormal];
    [_refreshBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [_refreshBtn addTarget:self action:@selector(getData) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_refreshBtn];
    
     _refreshBtn.frame = CGRectMake(0, ScreenHeight/2 + 100, ScreenWidth, 30);
     _refreshBtn.hidden = YES;

}


#pragma mark - UICollectionViewDelegate,UICollectionViewDataSource

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _dataList.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellId forIndexPath:indexPath];
    cell.backgroundColor = [UIColor blackColor];
    [cell configPicCellWithData:_dataList[indexPath.row]];
    
    return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(ScreenWidth,ScreenHeight);
}
- (CGFloat)collectionView: (UICollectionView *)collectionView
                   layout: (UICollectionViewLayout*)collectionViewLayout
minimumLineSpacingForSectionAtIndex: (NSInteger)section{
    
    return 0.000000f;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
 
    CollectionViewCell *cell = (CollectionViewCell*)[collectionView cellForItemAtIndexPath:indexPath];
    
    ChatImageBrowserView *view = [[ChatImageBrowserView alloc]initWiththumbnail:cell.image.image fromRect:self.view.bounds];
    
     UIView *keyWindow = [UIApplication sharedApplication].keyWindow;
     [keyWindow addSubview:view];

}



@end
